<?php

namespace app\common\helper;

use app\common\exception\BusinessException;

class WxHelper
{
    /**
     * createWxQrcode
     * @param string $access_token
     * @param string $path
     * @param string $scene
     * @return string
     * @throws BusinessException
     */
    public static function createWxQrcode(string $access_token, string $path, string $scene): string
    {
        // 接口名称
        $name = 'create_wx_a_qrcode';

        // 接口地址
        $api = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $access_token;

        // 请求接口
        $request = [
            'page' => $path,
            'scene' => $scene,
            'check_path' => true,
        ];
        $response = curl($api, json_encode($request));

        // 检查返回内容
        if (!$response) {
            throw new BusinessException("{$name}服务接口未响应内容");
        }

        // 检查响应内容
        $responseJson = json_decode($response, true);
        if (isset($responseJson['errcode']) && $responseJson['errcode'] !== '0') {
            $errStr = "错误码:{$responseJson['errcode']},错误信息:{$responseJson['errmsg']}";
            throw new BusinessException("{$name}服务异常,$errStr");
        }

        // 返回
        return $response;
    }

    /**
     * code_t_session
     * @param string $appId
     * @param string $secret
     * @param string $js_code
     * @param string $grant_type
     * @return array
     * @throws BusinessException
     */
    public static function code2Session(string $appId, string $secret, string $js_code, string $grant_type = 'authorization_code'): array
    {
        // 接口名称
        $name = 'code_t_session';

        // 接口地址
        $api = 'https://api.weixin.qq.com/sns/jscode2session?';

        // 请求接口
        $request = [
            'appid' => $appId,
            'secret' => $secret,
            'js_code' => $js_code,
            'grant_type' => $grant_type,
        ];
        $api .= http_build_query($request);
        $response = curl($api, []);

        // 检查响应内容
        $response = checkJsonApiResponse($name, $response, []);
        if (isset($response['errcode']) && $response['errcode'] !== '0') {
            $errStr = "错误码:{$response['errcode']},错误信息:{$response['errmsg']}";
            throw new BusinessException("{$name}服务异常,$errStr");
        }
        if (!$response['openid'] || !$response['session_key']) {
            $errStr = "缺少openid和session_key";
            throw new BusinessException("{$name}服务异常,$errStr");
        }

        // 返回
        return [
            'openid' => $response['openid'],
            'session_key' => $response['session_key'],
            'unionid' => $response['unionid'] ?? '',
        ];
    }

    /**
     * getAccessToken
     * @param string $appId
     * @param string $secret
     * @param string $grant_type
     * @return array
     * @throws BusinessException
     */
    public static function getAccessToken(string $appId, string $secret, string $grant_type = 'client_credential'): array
    {
        // 接口地址
        $api = 'https://api.weixin.qq.com/cgi-bin/token?';

        // 请求接口
        $request = [
            'appid' => $appId,
            'secret' => $secret,
            'grant_type' => $grant_type,
        ];
        $api .= http_build_query($request);
        $response = curl($api, []);

        // 检查响应内容
        $name = 'getAccessToken';
        $response = checkJsonApiResponse($name, $response, []);
        if (isset($response['errcode']) && $response['errcode'] !== '0') {
            $errStr = "错误码:{$response['errcode']},错误信息:{$response['errmsg']}";
            throw new BusinessException("{$name}服务异常,$errStr");
        }

        // 返回
        return [
            'access_token' => $response['access_token'],
            'expires_in' => $response['expires_in'],
        ];
    }

    /**
     * getUserPhoneNumber
     * @param string $access_token
     * @param string $code
     * @return string
     * @throws BusinessException
     */
    public static function getUserPhoneNumber(string $access_token, string $code): string
    {
        // 接口名称
        $name = 'getUserPhoneNumber';

        // 接口地址
        $api = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $access_token;

        // 请求接口
        $request = [
            'code' => $code,
        ];
        $response = curl($api, json_encode($request));

        // 检查返回内容
        if (!$response) {
            throw new BusinessException("{$name}服务接口未响应内容");
        }

        // 检查响应内容
        $responseJson = json_decode($response, true);
        if (isset($responseJson['errcode']) && $responseJson['errcode'] !== 0) {
            $errStr = "错误码:{$responseJson['errcode']},错误信息:{$responseJson['errmsg']}";
            throw new BusinessException("{$name}服务异常,$errStr");
        }

        // 返回
        return $responseJson['phone_info']['purePhoneNumber'] ?? '';
    }

    /**
     * sendCustomMessage
     * @param string $access_token
     * @param array $message
     * @throws BusinessException
     */
    public static function sendCustomMessage(string $access_token, array $message)
    {
        // 接口名称
        $name = 'sendCustomMessage';

        // 接口地址
        $api = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;

        // 请求接口
        $response = curl($api, json_encode($message, JSON_UNESCAPED_UNICODE));

        // 检查返回内容
        if (!$response) {
            throw new BusinessException("{$name}服务接口未响应内容");
        }

        // 检查响应内容
        $responseJson = json_decode($response, true);
        if (isset($responseJson['errcode']) && $responseJson['errcode'] !== 0) {
            $errStr = "错误码:{$responseJson['errcode']},错误信息:{$responseJson['errmsg']}";
            throw new BusinessException("{$name}服务异常,$errStr");
        }
    }

    /**
     * sendSubscribeMessage
     * @param string $access_token
     * @param array $message
     * @throws BusinessException
     */
    public static function sendSubscribeMessage(string $access_token, array $message)
    {
        // 接口名称
        $name = 'sendSubscribeMessage';

        // 接口地址
        $api = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;

        // 请求接口
        $response = curl($api, json_encode($message, JSON_UNESCAPED_UNICODE));

        // 检查返回内容
        if (!$response) {
            throw new BusinessException("{$name}服务接口未响应内容");
        }

        // 检查响应内容
        $responseJson = json_decode($response, true);
        if (isset($responseJson['errcode']) && $responseJson['errcode'] !== 0) {
            $errStr = "错误码:{$responseJson['errcode']},错误信息:{$responseJson['errmsg']}";
            throw new BusinessException("{$name}服务异常,$errStr");
        }
    }
}